package com.lk.utils.service;

import com.lk.utils.log.JLog;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.IInterface;

public abstract class AbsServiceControllerHelper<T extends IInterface> {

	private final static JLog LOG = new JLog("AbsServiceControllerHelper", true, JLog.LogType.INFO);
	
	protected T mFeature;
	
	protected Context mContext;
	
	private IServiceConnectionListener mServiceConnectionListener;
	
	public void connectService(IServiceConnectionListener serviceConnectionListener){
		mServiceConnectionListener = serviceConnectionListener;
		if(mFeature == null){
			try{
				LOG.print("bind kernal service");
				mContext.bindService(getServiceIntent(), mServiceConnection, Context.BIND_AUTO_CREATE);
				LOG.print("bind kernal service finish");
			}catch(Exception e){
				LOG.print("bing kernal service exception");
				mContext.stopService(getServiceIntent());
				mContext.startService(getServiceIntent());
				mContext.bindService(getServiceIntent(), mServiceConnection, Context.BIND_AUTO_CREATE);
			}
		}else{
			serviceConnectionListener.notifyServiceConnected();
		}
	}
	
	/**
	 * 
	 */
	private ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName componentName, IBinder binder) {
			doConnected(componentName, binder);
			if(mServiceConnectionListener != null){
				mServiceConnectionListener.notifyServiceConnected();
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName componentName) {
			doDisconnected(componentName);
			mFeature = null;
		}

	};
	
	public T getFeature(){
		return mFeature;
	}
	
	/**
	 * 释放资源
	 */
	public void release(){
		
		mContext.unbindService(mServiceConnection);
		doRelease();
		mFeature = null;
	}
	
	/**
	 * 释放子类资源
	 */
	protected abstract void doRelease();
	
	/**
	 * 连接服务成功
	 * @param componentName
	 * @param binder
	 */
	protected abstract void doConnected(ComponentName componentName, IBinder binder);
	
	/**
	 * 断开服务
	 */
	protected abstract void doDisconnected(ComponentName componentName);
	
	/**
	 * 获取连接的服务
	 */
	protected abstract Intent getServiceIntent();
	
	
	public interface IServiceConnectionListener{
		/**
		 * 通知服务连接成功
		 */
		public void notifyServiceConnected();
	}
	
	
	
}
